import { Injectable, Inject } from '@nestjs/common'
import { RedisClientType } from 'redis'

@Injectable()
export class RedisService {
  @Inject('REDIS_CLIENT')
  private redisClient: RedisClientType

  private POS_KEY = 'suzhou'

  async get(key: string) {
    return await this.redisClient.get(key)
  }

  async set(key: string, value: string | number, ttl?: number) {
    await this.redisClient.set(key, value)

    if (ttl) {
      await this.redisClient.expire(key, ttl)
    }
    return '保存成功'
  }

  /**
   * 添加位置信息
   * @param posName 房源id
   * @param posLoc 房源坐标
   */
  async addGeo(posName: string, posLoc: [number, number]) {
    await this.redisClient.geoAdd(this.POS_KEY, {
      member: posName,
      longitude: posLoc[0],
      latitude: posLoc[1],
    })
  }

  /**
   * 获取redis位置信息
   * @param posName
   * @returns
   */
  async geoPos(posName: string) {
    return await this.redisClient.geoPos(this.POS_KEY, posName)
  }

  /**
   * 中心经纬度搜索附近经纬度
   * @param posCenter 中心经纬度
   * @param radius 搜索半径
   * @returns
   */
  async geoSearch(posCenter: [number, number], radius: number) {
    const positions = await this.redisClient.geoRadius(
      this.POS_KEY,
      {
        longitude: posCenter[0],
        latitude: posCenter[1],
      },
      radius,
      'km',
    )
    const list = []
    for (let i = 0; i < positions.length; i++) {
      const pos = positions[i]
      const res = await this.geoPos(pos)
      list.push({
        id: pos,
        ...res[0],
      })
    }
    return list
  }

  /**
   * 删除单个坐标点
   * @param posName 房源id
   */
  async removeGeo(posName: string) {
    await this.redisClient.zRem(this.POS_KEY, posName)
  }

  async setHash(hash_id: string, hash_key: string, hash_value: string) {
    await this.redisClient.hSet(hash_id, hash_key, hash_value)
  }

  async getHash(hash_id: string, hash_key: string) {
    return await this.redisClient.hGet(hash_id, hash_key)
  }

  async getHashAll(hash_id: string) {
    return await this.redisClient.hGetAll(hash_id)
  }

  async removeHash(hash_id: string, hash_key: string) {
    await this.redisClient.hDel(hash_id, hash_key)
  }
}
